package com.zfc.life.utils.file;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.zfc.life.config.QiNiuYunConfig;
import com.zfc.life.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author zfc
 * @Date 2024/6/3 9:20
 * @Description QiniuUtil
 */
public class QiniuUtil {

    //创建七牛云配置对象
    private static Configuration cfg = new Configuration(Zone.autoZone());

    //密钥配置
    private static Auth auth = Auth.create(QiNiuYunConfig.qiniuAccessKey, QiNiuYunConfig.qiniusecretKey);


    /**
     * 获取上传tonken
     *
     * @return
     */
    public static String getUpToken() {
        return auth.uploadToken(QiNiuYunConfig.qiniuBucketName);
    }

    public static String uploadFile(MultipartFile file) {
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新的文件名
            String objectName = UUID.randomUUID().toString() + extension;

            //创建上传管理器
            UploadManager uploadManager = new UploadManager(cfg);

            //sm-frontend/css/2024/3/417a6320-a0be-4e90-a7ab-ebd1fe320269.png
            String directory = QiNiuYunConfig.directory + byFileSelectDirectory(objectName) + StringUtils.yearAndMonthFolder() + objectName;

            //执行上传文件
            Response response = uploadManager.put(file.getBytes(), directory, getUpToken());

            //解析上传结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            String fileKey = putRet.key; // 获取上传文件的key http:/qiniuyun.zfc.life/sm-frontend/2024/3/bg1.gif

            System.out.println("资源上传成功！ fileKey = "+directory);

            // 返回文件在七牛云的访问URL
            return QiNiuYunConfig.qiniuImageDomain + fileKey;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除图片
     *
     * @param fileName 图片名称
     * @return
     */
    public static boolean delImages(String fileName) {

        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            //将图片地址分割；只获取目录后的地址；域名不要
            String[] split = fileName.split(QiNiuYunConfig.qiniuImageDomain);
            //判断图片是否存在
            FileInfo stat = bucketManager.stat(QiNiuYunConfig.qiniuBucketName, split[1]);
            if (stat != null) {
                bucketManager.delete(QiNiuYunConfig.qiniuBucketName, split[1]);
                return true;
            }
            return false;
        } catch (QiniuException e) {
            throw new RuntimeException(e.response.toString());
        }
    }

    public static String byFileSelectDirectory(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

        if (suffix.equals("jpg") || suffix.equals("png") || suffix.equals("gif") || suffix.equals("jpeg")) {
            return "image/";
        } else if (suffix.equals("mp4") || suffix.equals("avi") || suffix.equals("rmvb")) {
            return "video";
        }
        return "";
    }


}
